package com.fan.cachewebview.core

import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.webkit.WebResourceResponse
import com.fan.cachewebview.bean.WebResource
import com.fan.cachewebview.utils.AppUtils
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.net.HttpURLConnection
import java.util.*

/**
 * @description $
 * @date: 2022/2/23 16:10
 * @author: fan
 */
class WebResourceGenerator : WebResourceGenerateApi {

    private val KEY_CONTENT_TYPE = "Content-Type"

    override fun generate(resource: WebResource?, urlMime: String?): WebResourceResponse? {
        if (resource == null) {
            return resource
        }

        val headers = resource.responseHeaders
        var contentType: String? = null
        var charset: String? = null
        var myUrlMime = urlMime

        if (headers != null) {
            var contentTypeValue = getContentType(headers, KEY_CONTENT_TYPE)
            if (!TextUtils.isEmpty(contentTypeValue)) {

                val contentTypeArray = contentTypeValue!!.split(";").toTypedArray()
                if (contentTypeArray.isNotEmpty()) {
                    contentType = contentTypeArray[0]
                }

                if (contentTypeArray.size >= 2) {
                    charset = contentTypeArray[1]

                    // 字符集获取
                    val charsetArray = charset.split("=").toTypedArray()

                    if (charsetArray.size >= 2) {
                        charset = charsetArray[1]
                    }
                }
            }
        }

        if (!TextUtils.isEmpty(contentType)) {
            myUrlMime = contentType!!
        }
        if (TextUtils.isEmpty(myUrlMime)) {
            return null
        }

        // 具体资源数据内容
        val resourceBytes = resource.originBytes

        if (resourceBytes == null || resourceBytes.size < 0) {
            return null
        }

        /**
         * 304状态码 不是一种错误，而是对客户端有缓存情况下服务端的一种响应。
         */
        if (resourceBytes.isEmpty() && resource.responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
//            Log.d("fan", "304状态码下resourceBytes不得为空")
            return null;
        }

        // IO 操作
        val bis: InputStream = ByteArrayInputStream(resourceBytes)

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            val status = resource.responseCode
            var reasonPhrase = resource.reasonPhrase

            if (TextUtils.isEmpty(reasonPhrase)) {
                reasonPhrase = AppUtils.getPhrase(status)
            }

            return WebResourceResponse(
                myUrlMime,
                charset,
                status,
                reasonPhrase,
                resource.responseHeaders,
                bis
            )
        }
        return WebResourceResponse(myUrlMime, charset, bis)
    }

    private fun getContentType(headers: Map<String, String>?, key: String): String? {
        if (headers != null) {
            val value = headers[key]
            return value ?: headers[key.lowercase(Locale.getDefault())]
        }
        return null
    }
}